package com.promote.hotspot.server.hot;

import lombok.extern.slf4j.Slf4j;
import org.promote.hotspot.common.model.HotKeyModel;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * 计数器
 *
 * @author enping.jep
 * @date 2024/01/08 16:12
 **/
@Component
@Slf4j
public class HotSpotQueue {

    private static final AtomicLong TOTAL_COUNT = new AtomicLong();//原子类代表server实例接收到热点的总数

    private static final LongAdder EXPIRE_TOTAL_COUNT = new LongAdder();//过期的热点数量

    private static final BlockingQueue<HotKeyModel> QUEUE = new LinkedBlockingQueue<>(2000000); //生产者-消费者队列

    private static final LongAdder TOTAL_OFFER_COUNT = new LongAdder();//总共入队列的数量

    private static final LongAdder TOTAL_DEAL_COUNT = new LongAdder(); //总共处理的数量

    /**
     * HotKeyModel数据入队
     *
     * @param hotKeyModel 热点数据
     */
    public void put(HotKeyModel hotKeyModel) {
        try {
            QUEUE.put(hotKeyModel);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对过期的热点数量进行累计
     */
    public void addExpireTotalCount() {
        EXPIRE_TOTAL_COUNT.increment();
    }

    /**
     * 总量计数
     */
    public void addTotalCount() {
        TOTAL_COUNT.incrementAndGet();
    }

    public void addTotalOfferCount() {
        TOTAL_OFFER_COUNT.increment();
    }

    public HotKeyModel takeItemFromQueue() {
        try {
            return QUEUE.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean hasItem() {
        return !QUEUE.isEmpty();
    }

    public void addTotalDealCount() {
        TOTAL_DEAL_COUNT.increment();
    }
}
